let App = getApp();
var i;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    disabled: false,
    nav_select: false, // 快捷导航
    name: '',
    region: '',
    phone: '',
    detail: '',
    wxapp_id:'',
    error: '',
    tempFilePaths:[],
    showImages: [],
    images:[],
    check_sex:1,
    type:1,
    img_num:0,

    age_group: [
      { name: '20以下', value: 0, checked: true },
      { name: '21岁~25岁', value: 1, checked: false },
      { name: '26岁~30岁', value: 2, checked: false },
      { name: '31岁~35岁', value: 3, checked: false },
      { name: '35岁以上', value: 4, checked: false },
    ],
    sex_index: 0,//年龄段的下标
    is_age_group: 0,//是否选择年龄段 1=是，0=否

    date:'',

    //经常出没 区信息
    dist_res: [],
    dist_index_arr:[],//多选下标选中数组
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      city_id: 3
    });
    //获取 杭州市 的区信息
    this.getDistrict();
  },

  onShow: function () {
    this.is_login();
    // 获取当前用户信息
    //this.getUserDetail();
    i = 0;
  },

  is_login:function(){
    App._get('user/is_login', {}, function (result) {
      if(result.data.code == 2){
        App.showIsLogin(result.msg, function () {
          wx.navigateBack();
        });
      }
    });
  },

  //获取 杭州市 的区信息
  getDistrict:function(){
    let _this = this;
    let city_id = this.data.city_id;
    App._get('Shopping_mall/getDistrict_two', { city_id: city_id}, function (result) {
      _this.setData({
        dist_res: result.data.list
      });
    });
  },

  /**
   * 获取当前用户信息
   */
  getUserDetail: function () {
    let _this = this;
    App._get('user.index/detail', {}, function (result) {
      
      _this.setData(result.data);
      _this.setData({
        check_sex: result.data.userInfo.gender
      })
      //console.log(result.data);
    });
  },

  /**
   * 表单提交
   */
  saveData: function(e) {
    let _this = this,
      values = e.detail.value
    values.region = this.data.region;
    values.sex = this.data.check_sex;
    values.images = this.data.images;
    values.type = this.data.type;

    values.is_age_group = this.data.is_age_group;//是否选择
    if (this.data.is_age_group == 1) {
      values.age_group = this.data.age_group[this.data.sex_index].value;
    }else{
      values.age = this.data.date;
    }
    values.dist = this.data.dist_index_arr;
    
    // console.log(values);
    // return false;
    // 记录formId
    App.saveFormId(e.detail.formId);

    //表单验证
    if (!_this.validation(values)) {
      App.showError(_this.data.error);
      return false;
    }

    // 按钮禁用
    _this.setData({
      disabled: true
    });

    //图片上传
    //_this.btn_up();
    //console.log(values);
    //提交到后端
    App._post_form('address/addDate', values, function(result) {
      // App.showSuccess(result.msg, function() {
      //   wx.navigateBack();
      // });
      console.log(result);
    }, false, function() {
      // 解除禁用
      _this.setData({
        disabled: false
      });
    });
  },
  
  

  /**
   * 表单验证
   */
  validation: function(values) {
    if (values.name === '') {
      this.data.error = '真实姓名不能为空';
      return false;
    }
    if (values.sex == 0) {
      this.data.error = '请选择性别';
      return false;
    }
    
    if (values.age == '') {
      this.data.error = '年龄不能为空';
      return false;
    }

    if (values.height == 0) {
      this.data.error = '身高不能为空';
      return false;
    }

    if (!this.data.region) {
      this.data.error = '籍贯不能空';
      return false;
    }

    if (this.data.dist_index_arr.length<=0) {
      this.data.error = '请选择您经常出没的地区';
      return false;
    }

    
    // if (values.detail === '') {
    //   this.data.error = '现今所在不能为空';
    //   return false;
    // }

    if (this.data.images.length < 1) {
      this.data.error = '请上传至少一张图片';
      return false;
    }

    return true;
  },

  /**
   * 修改地区
   */
  bindRegionChange: function(e) {
    this.setData({
      region: e.detail.value
    })
  },

  /**
   * 获取微信地址
   */
  chooseAddress: function() {
    let _this = this;
    wx.chooseAddress({
      success: function(res) {
        _this.setData({
          name: res.userName,
          phone: res.telNumber,
          region: [res.provinceName, res.cityName, res.countyName],
          detail: res.detailInfo
        });
      }
    })
  },

  // radio: function (e) {
  //   this.setData({
  //     guige_key02: e.currentTarget.dataset.id
  //   })
  //   console.log(e.currentTarget.dataset.id)
  // },

  radioChange: function (e) {
    this.setData({
      check_sex: e.detail.value
    })
  },

  radioStatusChange:function(e){
    this.setData({
      type: e.detail.value
    })
  },

  // img_item: function (e) {
  //   var that = this;
  //   wx.chooseImage({
  //     count: 3,
  //     sizeType: ['original'],
  //     sourceType: ['album', 'camera'],
  //     success: function (res) {
  //       that.setData({
  //         'tempFilePaths': res.tempFilePaths
  //       })
  //       that.btn_up();
  //     }
  //   })
  // },

   // btn_up: function (e) {
  //   var that = this;
  //   wx.uploadFile({
  //     url: App.api_root + 'address/addImage', // 仅为示例，非真实的接口地址
  //     filePath: that.data.tempFilePaths[i],
  //     name: 'image',
  //     formData: {
  //       wxapp_id: App.siteInfo.uniacid
  //     },
  //     success(res) {
  //       var res = JSON.parse(res.data);
  //       that.setData({
  //         ['images[' + i + ']']: res.data
  //       })
  //       console.log(that.data.images);
  //       i++;
  //       if (i < that.data.tempFilePaths.length) {
  //         that.btn_up();
  //       }
  //     }
  //   })
  // },
  //长按删除
  bindlongpressimg: function (e) {
    let that = this;
    let key = e.target.dataset.id;
    let imagesArr = that.data.images;
    let showImagesArr = that.data.showImages;
    
    imagesArr.splice(key, 1);
    showImagesArr.splice(key, 1);
    that.setData({
      images: imagesArr,
      showImages: showImagesArr
    })

  },

  //查看图片
  previewImage: function (e) {
    let key = e.target.dataset.id;
    let imgSrc = this.data.showImages;

    wx.previewImage({
      current: imgSrc[key],
      urls: imgSrc
    })
  },

  //发起图片提交
  img_item: function (e) {
    var that = this;
    if (that.data.showImages.length > 3) {
      App.showError('只可上传3张图片', function () {
      });
      return false;
    }

    wx.chooseImage({
      count: 3,
      sizeType: ['original'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        if ((that.data.showImages.length + res.tempFilePaths.length) > 3) {
          App.showError('只可上传3张图片', function () {
          });
          return false;
        }
        that.setData({
          'tempFilePaths': ''
        })
        i = 0;

        that.setData({
          'tempFilePaths': res.tempFilePaths
        })
        //console.log(that.data.tempFilePaths);
        that.btn_up();
      }
    })
  },

  //提交图片
  btn_up: function (e) {
    var that = this;
    let token = wx.getStorageSync('token');
    wx.showLoading({
      title: '图片上传中...',
    })
    wx.uploadFile({
      url: App.api_root + 'address/addImage', // 仅为示例，非真实的接口地址
      filePath: that.data.tempFilePaths[i],
      name: 'file',
      formData: {
        wxapp_id: App.siteInfo.uniacid,
        token: token
      },
      success(res) {
        //console.log(res);
        let arr = JSON.parse(res.data);
        if (arr.code == 1) {
          let arr2 = JSON.parse(arr.data);
          var showImagesArr = that.data.showImages;
          showImagesArr.push(App.root + arr2.url);
          var imagesArr = that.data.images;
          imagesArr.push(arr2.url);
          that.setData({
            'showImages': showImagesArr,
            'images': imagesArr
          })
          i++;
          if (i < that.data.tempFilePaths.length) {
            that.btn_up();
          }
        }else{
          App.showError(arr.msg);
        }
        wx.hideLoading();
      }
    })
  },


  //是否选择年龄段
  radioChangeSex: function (e) {
    let index = e.detail.value;
    this.setData({
      is_age_group: index
    })
  },
  //修改年龄段
  bindPickerChange: function (e) {
    let index = e.detail.value;
    console.log(index);
    this.setData({
      sex_index: index
    })
  },
  //日期改变
  bindDateChange: function (e) {
    //console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      date: e.detail.value
    })
  },

  //改变 经常出没
  checkboxChange: function (e) {
    // let dist_res = this.data.dist_res;
    // let numbers = e.detail.value;
    // for (let i = 0; i < dist_res.length;i++){
    //   let id = dist_res[i]['id'];
    //   if (numbers.includes(id.toString())) {
    //     dist_res[i]['checked'] = true;
    //   } else {
    //     dist_res[i]['checked'] = false;
    //   }
    // }
    this.setData({
      //dist_res: dist_res,
      dist_index_arr: e.detail.value
    })
  },

})